package com.oracle.zebrafreelytraveling.ui.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.model.NaviInfoModel;
import com.oracle.zebrafreelytraveling.map.MapInfoAdapter;
import com.oracle.zebrafreelytraveling.map.MapUtil;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.NaviActivity;
import com.oracle.zebrafreelytraveling.utils.UserUtil;

import java.util.List;

/**
 * Created by yydcnjjw on 2017/7/16.
 */

public class SuspendService extends Service {

    private RelativeLayout mSuspendLayout;
    private WindowManager.LayoutParams mParams;
    private WindowManager mWindowManager;

    private ImageView mSuspendIcon;
    private RecyclerView mViewLocationRecycle;
    private CommonAdapter<NaviInfoModel.bean> mViewLocationAdapter;

    private MapUtil mapUtil;
    private NaviInfoModel model;
    private LatLonPoint from;
    private LatLonPoint to;
    private int position;

    private boolean isRecycleVisibly = false;

    @Override
    public void onCreate() {
        super.onCreate();
        createFloatView();
        initRecycle();
        initLocation();
    }

    private void initRecycle(){
        model = UserUtil.getUserNaviModelList();
        if (model == null){
            return;
        }
        List<NaviInfoModel.bean> modelList = model.getNaviInfoModelList();
        mViewLocationRecycle.setLayoutManager(new LinearLayoutManager(this));
        mViewLocationRecycle.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        mViewLocationAdapter = new CommonAdapter<NaviInfoModel.bean>(this, R.layout.item_suspend_list_info, modelList) {
            @Override
            protected void convert(ViewHolder holder, NaviInfoModel.bean bean, int position) {
                holder.setText(R.id.suspend_name, bean.getTitle());
            }
        };
        mViewLocationAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int posi) {
                to = new LatLonPoint(modelList.get(position).getLatitude(),
                        modelList.get(position).getLongitude());
                position = posi;
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mViewLocationRecycle.setAdapter(mViewLocationAdapter);
    }

    private void initLocation(){
        mapUtil = new MapUtil(new MapInfoAdapter() {
            @Override
            public void locationInfo(AMapLocation location) {
                super.locationInfo(location);
                if (location != null) {
                    from = new LatLonPoint(location.getLatitude(), location.getLongitude());
                    NaviActivity.startNaviActivity(SuspendService.this, from, to, position);
                }
            }
        });
    }

    private void createFloatView(){
        mParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        //设置window type
        mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //设置图片格式，效果为背景透明
//        mParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        mParams.flags =  WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        mParams.gravity = Gravity.LEFT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        mParams.x = 0;
        mParams.y = 0;
        //设置悬浮窗口长宽数据
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.height = WindowManager.LayoutParams.MATCH_PARENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在的布局
        mSuspendLayout = (RelativeLayout) inflater.inflate(R.layout.service_suspend_layout, null);
        mWindowManager.addView(mSuspendLayout, mParams);
        mSuspendIcon = (ImageView) mSuspendLayout.findViewById(R.id.suspend_icon);
        mViewLocationRecycle = (RecyclerView) mSuspendLayout.findViewById(R.id.suspend_view_location_recycle);

        mSuspendIcon.setOnTouchListener((v, e) -> {
            //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
            mParams.x = (int) e.getRawX() - mSuspendIcon.getMeasuredWidth();
            mParams.y = (int) e.getRawY() - mSuspendLayout.getHeight();
            mWindowManager.updateViewLayout(mSuspendLayout, mParams);
            return false;
        });

        mSuspendIcon.setOnClickListener(v -> {
            if (!isRecycleVisibly){
                mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                mViewLocationRecycle.setVisibility(View.VISIBLE);
                mParams.flags =  WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
                mWindowManager.updateViewLayout(mSuspendLayout, mParams);
                isRecycleVisibly = true;
            } else {
                mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
                mViewLocationRecycle.setVisibility(View.GONE);
                mParams.flags =  WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                mWindowManager.updateViewLayout(mSuspendLayout, mParams);
                isRecycleVisibly = false;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSuspendLayout != null){
            mWindowManager.removeView(mSuspendLayout);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
